﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using Telerik.Framework.Search;
using Telerik.Search;
using Telerik.Search.Engine;

namespace SelArom.Net.Sitefinity.Pages
{
	/// <summary>
	/// Custom 404 page, searches and displays items related to missing page
	/// </summary>
	public class Error404 : Page
	{
		private IList<ResultItem> results;
		protected IList<ResultItem> SearchResults
		{
			get
			{
				if (results == null)
				{
					results = new List<ResultItem>();
					// only handle pages
					var url = Request.Params["aspxerrorpath"];
					string[] req;
					if (string.IsNullOrEmpty(url))
					{
						url = Request.Url.Query;
						if (string.IsNullOrEmpty(url) || !url.Contains("404")) return results;
						req = url.Replace('_', ' ').Split('/');
						if (req.Length < 3) return results;

						// clear non-useful items
						req[0] = req[1] = req[2] = "";

					}
					else
						req = url.Replace('_', ' ').Split('/');

					// create query from url
					var sb = new StringBuilder();
					foreach (var s in req)
					{
						if (!s.StartsWith("default") && s.Length > 1)
							sb.Append(HttpUtility.UrlDecode(Regex.Replace(s, "\\..*", "") + " "));
					}
					var query = sb.ToString();
					if (query.Trim().Length <= 0) return results;
					int count;

					// get search indexes
					var indexManager = new IndexDataManager();
					var services = indexManager.GetServices();
					if (services.Count < 1) return results;
					var index = services[0] as IIndexingServiceInfo;
					if (index == null) return results;

					// finally search
					results = SearchManager.Search(query, index.Name, 0, 5, "AnyWord", out count);
				}
				return results;
			}
		}

		protected override void Render(HtmlTextWriter writer)
		{
			base.Render(writer);
			Response.StatusCode = 404;
		}
	}
}